from kinect import *
import numpy as np
from numpy.random import random as rand
from time import sleep
from Blender import *
import Blender, meshtools

def draw_mesh(mesh):
	"""
	Draw the Blender mesh
	"""
	Blender.NMesh.PutRaw(mesh,"obj",1)
	Blender.Redraw()

def create_mesh(data=None):
	"""
	Create a Kinect/Random mesh
	"""
	mesh = Blender.NMesh.GetRaw()
	
	if data!=None:
		data.resize((480, 640))
		for y in range(0,480,5):
			for x in range(0,640,5):
				zz = data[y,x]
				if(zz<1000):
					xx = (x-320)*(zz-10)*0.0021 #This 'calibration' copied using Zephod's windows software - because it 'just works'
					yy = (y-240)*(zz-10)*0.0021
					zz-=200
					mesh.verts.append(NMesh.Vert(xx, yy, -zz))
	else:
		mesh.verts.append(NMesh.Vert(rand(), rand(), rand()))
		
	return mesh	
	

lin = MinimalListener()
kf = KinectFinder()
k = kf.GetKinect()
k.AddListener(lin)

while(True):	
	mesh = create_mesh(np.array(k.mDepthBuffer))
	#mesh = create_mesh()
	draw_mesh(mesh)